<script setup>
import _ from "lodash";
import {useCommonStore} from "@jzl/stores";
import {computed, onBeforeMount, onMounted, watch} from "vue";
import {useRoute, useRouter} from 'vue-router'
// import WorkHeader from './header.vue'
import { PAGE_OPEN_TYPE, $menuUtils } from "@jzl/utils";

const route = useRoute()
const router = useRouter()

const menus = computed(() => {
  return useCommonStore().layoutMenus;

  /*return layout.value === "mix" && device.value !== "mobile"
    ? subMenuData.value
    : menus;*/
});

const defaultTopMenu = computed(() => {
  const layoutMenus = useCommonStore().layoutMenus;
  return _.find(layoutMenus, { is_default_menu: 1 }) || layoutMenus?.[0];
});

const isLayoutPath = computed(() => {
  return route.path === '/' || route.path === ''
})

const init = async () => {
  await useCommonStore().initLoginUser()
  let layoutMenus = await useCommonStore().initLayoutMenus()
  if (isLayoutPath.value) {
    goToDefaultMenu();
  }
}

const goToDefaultMenu = () => {
  // console.log(defaultTopMenu.value, useCommonStore().layoutMenus)
  if (defaultTopMenu.value) {
    $menuUtils.gotoMix(defaultTopMenu.value, router, null, PAGE_OPEN_TYPE.self)
  }
}

/*
const handleChangeMenu = (menu) => {
  this.changeMainMenu(menu);
  this.currentMainMenuId = _.get(menu, "tid");

  if (common.isMenu(menu)) {
    this.$router.replace({
      name: 'page',
      query: {
        menuId: menu.content_id
      }
    });
  } else if (menu.tid === "APPS" || common.isGroup(menu)) {
    this.$router.replace({
      name: 'app',
      query: {
        menuId: menu.group_id
      }
    });
  } else if (common.isApp(menu)) {
    if (menu.url) {
      window.location = `${menu.url}?appid=${menu.group_id}`;
    } else {
      this.$toast.fail('应用参数未配置，请完善配置信息！');
      // this.$message('应用参数未配置，请完善配置信息！');
    }
  } else {
    this.$toast.fail('应用设置不正确，请完善配置信息！');
    // this.$message('应用设置不正确，请完善配置信息！');
  }
}*/

/*
onBeforeMount(() => {
  useDataThemeChange().overallStyleChange(useCommonStore()?.layout?.overallStyle);
});
*/

onMounted(() => {
  init()
})

watch(() => route.path, (newPath) => {
  if (newPath === '/' || newPath === '') {
    init();
  }
})

watch(defaultTopMenu, () => {
  if(isLayoutPath.value) goToDefaultMenu()
})
</script>

<template>
  <div class="work-container" layout="horizontal">
    <!--<c-header ref="header" @change="handleChangeMenu"></c-header>-->
    <JLayoutNavHorizontal
      :menus="menus"
      :hide-setting="true"
    />
    <transition name="fade">
      <RouterView
        transition="fade"
        transition-mode="out-in"
        keep-alive
      />
    </transition>
  </div>
</template>
